package com.han.spider.cloudmeeting;

import com.han.spider.cloudmeeting.websocket.WebsocketClient;
import com.han.util.Dealer;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.WebSocket;
import org.java_websocket.drafts.Draft_6455;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Objects;
import java.util.Random;

/**
 * @Author: Hanjiafeng
 * @Date: 2020/6/28
 * @Desc:
 */
@Slf4j
public class MeetingManager {
    /**
     * group id
     */
    public static String gid;
    /**
     * 所有用户
     */
    public static List<String> uIdList;
    /**
     * 会议号
     */
    public static String nid;
    /**
     * 会议列表
     */
    public static List<String> meetingIdList;
    /**
     * 用户id
     */
    private final String userId;
    private WebsocketClient client;

    public MeetingManager(String userId) {
        this.userId = userId;
    }

    public WebsocketClient getClient() {
        return client;
    }

    public void connect(String url) throws URISyntaxException {
        log.info(userId + ":" + url);
        URI uri = new URI(url);
        client = new WebsocketClient(uri, new Draft_6455(), userId);
        client.connect();
        while (!client.getReadyState().equals(WebSocket.READYSTATE.OPEN)) {
            try {
                Thread.sleep(100);
                log.info(userId + ":" + "连接正在建立中");
            } catch (InterruptedException e) {
                e.printStackTrace();
                break;
            }
        }
        log.info(userId + ":" + "连接已建立");
    }

    /**
     * 创建并开始一个会议
     */
    public void startMeeting() {
        getAllUser();
        createMeeting();
        setAdviseMedia();
        setMember();
    }

    public void endMeeting() {
        getMeetingList();
        while (Objects.isNull(meetingIdList)) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        for (String meetingId : meetingIdList) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            deleteMeeting(meetingId);
        }
    }

    /**
     * 获取用户信息,主要是gid
     */
    public void getUserInfo() {
        send("{\"id\": 0, \"method\": \"contact.getUserInfo\"}");
        while (Objects.isNull(MeetingManager.gid)) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取所有用户
     */
    public void getAllUser() {
        send("{\"id\": \"1\",\"method\": \"contact.search\",\"params\":{\"IgnoreChild\": true,\"gid\": \"" + gid + "\",\"levels\": [1],\"location\": {\"begin\": 0, \"end\": 20000},\"types\": [0, 65536, 131072, 262144]}}");
    }

    /**
     * 创建会议
     */
    public void createMeeting() {
        send("{\"id\":2,\"method\":\"call.create\",\"params\":{\"name\":\"云视频会议\",\"media\":{\"bmax\":1000,\"demo\":{\"bmax\":4000}},\"gid\":\"" + gid + "\",\"property\":{\"password\":\"\",\"closeMicWhenJoin\":true,\"openMicBySelf\":true,\"initRole\":\"member\",\"demoPermission\":\"all\",\"allowJoinWithoutInvited\":true,\"allowJoinBeforeModerator\":true,\"h323Enable\":false,\"record\":{\"enable\":true},\"liveControl\":{\"status\":\"open\",\"password\":\"\",\"accessType\":\"group\"},\"encryption\":{\"type\":1,\"enable\":false}},\"duration\":7200,\"titles\":{\"nid\":\"\",\"subTitles\":{\"enable\":false,\"size\":\"middle\",\"color\":\"#FFFFFF\",\"bg_color\":\"#B62E24\",\"bg_transparency\":\"0\",\"text\":\"\"},\"banner\":{\"enable\":false,\"position\":\"center\",\"size\":\"middle\",\"color\":\"#FFFFFF\",\"bg_color\":\"#B62E24\",\"bg_transparency\":\"0\",\"text\":\"\"}}}}");
        while (Objects.isNull(MeetingManager.uIdList)) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 设置不知道是啥
     */
    public void setAdviseMedia() {
        send("{\"id\":3,\"method\":\"call.setAdviseMedia\",\"params\":{\"nid\":\"" + nid + "\",\"medias\":[{\"operator\":4,\"streams\":[{\"attachment\":{\"rect\":[0,0,0,1,1],\"nids\":[],\"interval\":10},\"key\":\"patrol_1\",\"mode\":1,\"modeIndex\":0,\"type\":\"main\"}]},{\"operator\":5,\"streams\":[]}]}}");
    }

    /**
     * 设置成员
     */
    public void setMember() {
        Random random = new Random();
        List<String> memberList = Dealer.roll(uIdList, random.nextInt(10) + 5);
        StringBuilder userSb = new StringBuilder();
        for (String member : memberList) {
            userSb.append("\"").append(member).append("\"").append(",");
        }
        userSb.deleteCharAt(userSb.length() - 1);
        String data = "{\"id\":4,\"method\":\"call.setMember\",\"params\":{\"moderator\":\"" + userId + "\",\"nid\":\"" + nid + "\",\"visitors\":[],\"members\":[" + userSb + "]}}";
        send(data);
    }

    /**
     * 获取会议列表
     */
    public void getMeetingList() {
        send("{\"id\":5,\"method\":\"call.getList\",\"params\":{\"gid\":\"" + gid + "\",\"callType\":\"present\",\"location\":{\"begin\":0,\"end\":2999}}}");
    }

    public void deleteMeeting(String meetingId) {
        send("{\"id\":6,\"method\":\"call.delete\",\"params\":{\"nid\":\"" + meetingId + "\"}}");
    }

    private void send(String data) {
        log.info(userId + ":" + data);
        client.send(data);
    }

    public void close() {
        client.close();
    }
}
